#include "Tag.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string.h>
#include "util.h"
#include "jsmin.h"
#include "kit.h"

static int nextIndex = 0;

namespace phnq
{
	namespace phnqlets
	{
		static phnq::kit::log::Logger *log = phnq::kit::log::Logger::get("phnq::phnqlets::Tag");
		
		Tag::Tag(string type, string path)
		{
			log->debug("loading tag: %s (%s)", type.c_str(), path.c_str());
			
			this->type = type;
			this->path = path;
			this->index = nextIndex++;
			
			ifstream fin(path.c_str());
			string line;
			while(getline(fin, line))
			{
				if(line.length() > 3 && line[0] == '/' && line[1] == '/' && line[2] == '#')
				{
					string instr = line.substr(3);
					vector<string> comps = util_split_string(instr, " ");
					if(comps[0] == "depend")
					{
						deps.insert(comps[1]);
					}
				}
			}
		}

		Tag::~Tag()
		{
		}
	
		string Tag::getType()
		{
			return type;
		}
	
		string Tag::getTagFilePath()
		{
			return path;
		}

		int Tag::getIndex()
		{
			return index;
		}
	
		string Tag::getTagCode()
		{
			stringbuf buf;
			char c[1024];
			sprintf(c, "tags[%i] = function(parentTag){this.type=\"%s\";", index, type.c_str());
			buf.sputn(c, strlen(c));
		
			string tagFileStr = util_get_file_contents(getTagFilePath().c_str());
			buf.sputn(tagFileStr.c_str(), tagFileStr.length());

			strcpy(c, "\neval(tagFooter);};");
			buf.sputn(c, strlen(c));

			sprintf(c, "tags[%i].pool=[];", index);
			buf.sputn(c, strlen(c));

			return buf.str();
		}

		set<string> Tag::getDependencies()
		{
			return deps;
		}
	}
}
